package org.judking.CarKeeper.command.EarlyWarning;

import org.judking.CarKeeper.activity.MainActivity;
import org.judking.CarKeeper.command.BaseObdCommand;
import org.judking.CarKeeper.service.StcActivityService;

import android.os.Handler;
import android.os.Message;

public class SpeedDetector implements WarningDetector	 {
	private final int SPEED_UP_BOUNDARY = 50;
	private final int LOW_SPEED_BOUNADARY = 10;
	private final int TIME_TICK_LIMIT = 4;
	private double curSpeed;
	private boolean iSpeedUp = false;
	private Counter counter;
	
	
	public SpeedDetector()			{
		counter = new Counter(TIME_TICK_LIMIT);
	}

	@Override
	public synchronized void detect(BaseObdCommand command) {
		curSpeed =Double.parseDouble(command.getRipeData().toString());
		
		if(iSpeedUp == false)		{
			iSpeedUp = (curSpeed >= SPEED_UP_BOUNDARY) ? true : false;
		}
		else		{
			if(curSpeed <= LOW_SPEED_BOUNADARY)		{
				if(counter.tickOnce() == true)		{
					Message msg = StcActivityService.handler.obtainMessage(MainActivity.SPEED_CRASH);
					StcActivityService.handler.sendMessage(msg);
					iSpeedUp = false;
				}
			}
			else if(curSpeed > LOW_SPEED_BOUNADARY && curSpeed < SPEED_UP_BOUNDARY)		{
				iSpeedUp = false;
				counter.reset();
			}
			else if(curSpeed >= SPEED_UP_BOUNDARY)	{
				iSpeedUp = true;
				counter.reset();
			}
		}
	}

	public double getCurSpeed() {
		return curSpeed;
	}

}
